import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Form, FormProps, Input, Modal, Radio, Select, Tag } from 'antd';

import Upload from '@/components/upload';

import { store } from '@/store';

import Device, { DeviceRef } from '@/pages/equipment/defect/device';
import {
  proInspectionRecordQueryPointHasUnfinishedDefect,
  proInspectionRecordReport
} from '@/services/bizApi/shengchanxunjianjilujiekou';
import { Icon } from '@iconify/react/dist/iconify.js';

import { BizObject } from '.';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'edit' | 'detail';
          rowData: any;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [userData, setUserData] = useState<BASE.OrgUserInfochaxunduixiang[]>([]);
  const device = useRef<DeviceRef>(null);
  const [deviceDataSource, setDeviceDataSource] = useState<BIZAPI.EquInfoEntity[]>([]);
  const [prompt, setPrompt] = useState<boolean>(false);

  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values,
        inspectionFile: values.inspectionFile?.replace(/\?/g, ','),
        pointRecordId: args?.rowData.pointRecordId,
        abnormalHandleUserName: userData.filter(
          (item) => item.id === values.abnormalHandleUserId
        )[0]?.fullName,
        //组装生成缺陷数据
        defectReportReq: {
          equipmentName: values.equipmentName,
          equipmentCode: values.equipmentCode,
          equipmentLocation: values.equipmentLocation,
          site: values.site,
          defectLevel: values.defectLevel,
          faultType: values.faultType,
          defectDescription: values.defectDescription,
          defectAttachment: values.defectAttachment,
          defectType: values.defectType
        }
      };

      await proInspectionRecordReport(query);

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success('巡检记录保存成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        // 编辑回填数据
        if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
          // 回填数据
          form.setFieldsValue({
            ...arg.rowData,
            inspectionFile: arg.rowData.inspectionFile?.replace(/,/g, '?')
          });
        } else {
          form.resetFields();
        }

        //检查当前点位是否有异常未处理
        proInspectionRecordQueryPointHasUnfinishedDefect({
          id: arg.rowData?.pointId as unknown as string
        }).then((res) => {
          setPrompt(res.data as boolean);
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');
      return;
    }
    form.resetFields();
    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Modal
      maskClosable={false}
      title={
        <>
          {`${args?.rowData?.name}巡检记录`}{' '}
          {prompt && (
            <Tag icon={<Icon color={'red'} icon="ri:error-warning-fill"></Icon>} color="error">
              <span style={{ color: 'red', verticalAlign: 'text-bottom' }}>
                当前点位存在未处理的缺陷
              </span>
            </Tag>
          )}
        </>
      }
      width="50%"
      centered={true}
      footer={
        args?.type === 'detail' ? null : (
          <>
            <Button onClick={onSave} type="primary" loading={submit.loading}>
              保存
            </Button>
            <Button onClick={onCancel} loading={submit.loading}>
              取消
            </Button>
          </>
        )
      }
      open={open}
      loading={submit.loading}
      onOk={onSave}
      onCancel={onCancel}
    >
      <Form
        style={{ marginTop: '20px' }}
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="巡检描述"
          name="inspectionDesc"
          rules={[
            {
              required: false,
              message: '请输入巡检描述'
            }
          ]}
        >
          <Input.TextArea
            style={{ width: '100%' }}
            autoSize={{ minRows: 4, maxRows: 6 }}
            placeholder="请输入巡检描述"
          />
        </Form.Item>
        <Form.Item
          label="上传附件"
          name="inspectionFile"
          rules={[
            {
              required: false,
              message: '请上传附件'
            }
          ]}
        >
          <Upload
            listType="picture-card"
            multiple
            accept="image/*"
            disabled={args?.type === 'detail'}
          >
            <Icon icon="ri:upload-2-fill" />
            上传图片
          </Upload>
        </Form.Item>
        <Form.Item
          label="是否异常"
          name="normal"
          rules={[
            {
              required: true,
              message: '请选择是否异常'
            }
          ]}
        >
          <Radio.Group>
            <Radio value={true}>正常</Radio>
            <Radio value={false}>异常</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item dependencies={['normal']} noStyle>
          {({ getFieldValue }) => {
            const normal = getFieldValue(['normal']);
            if (normal === false) {
              return (
                <>
                  {/* <ProFormSelect
                    name="abnormalHandleUserId"
                    style={{ width: '100%' }}
                    label="异常处理人"
                    showSearch={true}
                    rules={[
                      {
                        required: true,
                        message: '请选择异常处理人'
                      }
                    ]}
                    placeholder="请选择异常处理人"
                    request={async () => {
                      const res = await orgUserInfoVoPage({
                        page: 1,
                        size: 1000
                      });
                      setUserData(res?.data?.records || []);
                      return (
                        res?.data?.records?.map((item) => {
                          return {
                            label: item?.fullName,
                            value: item?.id
                          };
                        }) || []
                      );
                    }}
                  /> */}
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      width: '100%',
                      padding: '20px 24px 10px'
                    }}
                  >
                    <div style={{ fontSize: '16px' }}>设备详情</div>
                    <Button
                      type="primary"
                      disabled={args?.type === 'detail'}
                      onClick={() => {
                        device.current?.open({
                          onSuccess: (rows) => {
                            form?.setFieldsValue({
                              equipmentName: rows?.[0]?.equipmentName,
                              equipmentCode: rows?.[0]?.equipmentCode,
                              equipmentLocation: rows?.[0]?.storageLocation
                            });
                            setDeviceDataSource(rows || []);
                          }
                        });
                      }}
                    >
                      设备关联
                    </Button>
                  </div>
                  <Form.Item
                    label="设备名称"
                    name="equipmentName"
                    rules={[
                      {
                        required: true,
                        message: '请输入设备名称'
                      }
                    ]}
                  >
                    <Input placeholder="请输入设备名称" disabled />
                  </Form.Item>
                  <Form.Item
                    label="设备编号"
                    name="equipmentCode"
                    rules={[
                      {
                        required: true,
                        message: '请输入设备编号'
                      }
                    ]}
                  >
                    <Input placeholder="请输入设备编号" disabled />
                  </Form.Item>
                  <Form.Item
                    label="设备位置"
                    name="equipmentLocation"
                    rules={[
                      {
                        required: false,
                        message: '请输入设备位置'
                      }
                    ]}
                  >
                    <Input placeholder="请输入设备位置" disabled />
                  </Form.Item>
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      width: '100%',
                      padding: '20px 24px 10px'
                    }}
                  >
                    <div style={{ fontSize: '16px' }}>缺陷详情</div>
                  </div>
                  <Form.Item
                    name="site"
                    label="站点"
                    rules={[{ required: true, message: '请选择站点' }]}
                  >
                    <Select
                      style={{
                        width: '100%'
                      }}
                      allowClear
                      placeholder="请选择站点"
                      options={(store.dict['productionSite'] || []).map((item) => ({
                        value: item.dicValue,
                        label: item.dicName
                      }))}
                    />
                  </Form.Item>
                  <Form.Item
                    label="缺陷等级"
                    name="defectLevel"
                    rules={[
                      {
                        required: true,
                        message: '请选择缺陷等级'
                      }
                    ]}
                  >
                    <Select
                      style={{
                        width: '100%'
                      }}
                      allowClear
                      placeholder="请选择缺陷等级"
                      options={[
                        {
                          label: '一级',
                          value: '一级'
                        },
                        {
                          label: '二级',
                          value: '二级'
                        },
                        {
                          label: '三级高',
                          value: '三级高'
                        },
                        {
                          label: '三级中',
                          value: '三级中'
                        },
                        {
                          label: '三级低',
                          value: '三级低'
                        }
                      ]}
                    />
                  </Form.Item>
                  <Form.Item
                    label="缺陷类型"
                    name="defectType"
                    rules={[
                      {
                        required: true,
                        message: '请选择缺陷类型'
                      }
                    ]}
                  >
                    <Select
                      style={{
                        width: '100%'
                      }}
                      allowClear
                      placeholder="请选择缺陷类型"
                      options={[
                        {
                          label: '设备缺陷',
                          value: 1
                        },
                        {
                          label: '生产缺陷',
                          value: 2
                        }
                      ]}
                    />
                  </Form.Item>
                  <Form.Item noStyle dependencies={['defectType']}>
                    {({ getFieldValue }) => {
                      const defectType = getFieldValue('defectType') || '';
                      return defectType == 1 ? (
                        <Form.Item
                          label="故障类型"
                          name="faultType"
                          rules={[
                            {
                              required: true,
                              message: '请选择故障类型'
                            }
                          ]}
                        >
                          <Select
                            style={{
                              width: '100%'
                            }}
                            allowClear
                            placeholder="请选择故障类型"
                            options={[
                              {
                                label: '设备',
                                value: '设备'
                              },
                              {
                                label: '电气',
                                value: '电气'
                              },
                              {
                                label: '仪控',
                                value: '仪控'
                              },
                              {
                                label: '土建',
                                value: '土建'
                              },
                              {
                                label: '车辆',
                                value: '车辆'
                              }
                            ]}
                          />
                        </Form.Item>
                      ) : null;
                    }}
                  </Form.Item>

                  <Form.Item
                    label="缺陷描述"
                    name="defectDescription"
                    rules={[
                      {
                        required: true,
                        message: '请输入缺陷描述'
                      }
                    ]}
                  >
                    <Input.TextArea
                      placeholder="请输入缺陷描述"
                      autoSize={{ minRows: 2, maxRows: 4 }}
                    />
                  </Form.Item>
                  <Form.Item
                    label="上传附件"
                    name="defectAttachment"
                    rules={[
                      {
                        required: false,
                        message: '请上传附件'
                      }
                    ]}
                  >
                    <Upload
                    // base64
                    //  accept="image/*"
                    >
                      <Button>上传</Button>
                    </Upload>
                  </Form.Item>
                  {/* end缺陷上报 */}
                </>
              );
            }
          }}
        </Form.Item>
      </Form>
      <Device ref={device} />
    </Modal>
  );
};

export default forwardRef(Edit);
